package com.kpijavatraining6.module2.actionTools;

import com.kpijavatraining6.module2.sessionTools.History;

import java.io.*;

public class Saver {
	private String user;
	
	public Saver(String newUser) {
		user = newUser;
    } 

	/**
	 * saveHistory method
	 * @param history
	 */
	public void saveHistory(History history){
        TestStep[] newHistory = new TestStep[history.MAX_LENGTH];
        int numberOfQuestions = history.getCurrentNumber();
        for(int i = numberOfQuestions - 1; i >= 0; i--) {
            newHistory[i] = history.pull();
        }
		try {
            File file = new File(user + ".txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            for( int i = 0; i < numberOfQuestions; i++) {
                createNewLine(i,bw);
                newHistory[i].printToFile(bw);
            }
            bw.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
	}
	private void createNewLine(int i, BufferedWriter bufferedWriter ) {
        if(i != 0) {
            try {
                bufferedWriter.newLine();
            }   catch (IOException e) {

            }
        }
    }
	
	public String getNewUserName() {
		return user;
	}
}
